package com.airforce.controller;

import com.airforce.config.Redisconfig;
import com.airforce.mappers.servicesMapper;
import com.airforce.mappers.wechat_userMapper;
import com.airforce.model.services;
import com.airforce.model.wechat_user;
import com.airforce.utils.HttpUtil;
import com.airforce.utils.MD5BASE64Util;
import com.airforce.utils.ResultCode;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;


@RequestMapping("app")
@RestController
public class wechatLogin {

    @Autowired
    Environment env;

//    private static final String appid="wxfdefd25bd3136be6";
//    private static final String secret="f09129c8f9cdb8531759d4998153fa6f";
    private static final String chartset="UTF-8";
    private  final static Logger logger=LoggerFactory.getLogger(wechatLogin.class);

    @Autowired
    wechat_userMapper wechat_userMapper;



    @Autowired
    servicesMapper servicesMapper;

    @Autowired
    Redisconfig redisconfig;


    @Value("${salt}")
    private String salt;

    @GetMapping("login")
    public Object wechalogin(@RequestParam String code){

        String appid=env.getProperty("wechar.appid");
        String secret=env.getProperty("wechar.secret");

//        System.out.println("获取code"+code);
        String getUrl="https://api.weixin.qq.com/sns/jscode2session?appid="+
        appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";

        HttpUtil httpUtil=new HttpUtil();
       String result= httpUtil.doGet(getUrl,chartset);
        JSONObject jsonObject=JSONObject.fromObject(result);
        String session_key= (String) jsonObject.get("session_key");
        String openid= (String) jsonObject.get("openid");

//        Jedis jedis=new Jedis(redisconfig.getHost(),redisconfig.getPort());
        String   token=MD5BASE64Util.base64encode(session_key+","+openid+","+salt);

//        System.out.println("openid"+openid+"token:"+token);

//        jedis.set(openid,token);
        return ResultCode.SUCCESS.result(token);
    }



    @PostMapping(value = "register")
    public Object app_register(@ApiParam("会话临时code")@RequestParam String token,
                               @ApiParam("用户信息") @RequestParam String userInfo,
                               @ApiParam("分享人名称") @RequestParam(required = false) String ShareNickName,
                               @ApiParam("分享人ID") @RequestParam(required = false) Integer ShareId) throws UnsupportedEncodingException {

        JSONObject jsonObject=JSONObject.fromObject(userInfo);
        String registerUserName=java.net.URLEncoder.encode(jsonObject.getString("nickName"),"UTF-8");

        try {
            if (ShareNickName != null && ShareNickName != "" && ShareId != 0) {
                int id = ShareId;
                logger.info(jsonObject.getString("nickName")+"注册成功，答题分享人为：" + java.net.URLDecoder.decode(ShareNickName));
                wechat_user user_info = wechat_userMapper.selectByIdAndName(id);
                int sharenum = user_info.getSharenum();
                int answernum = user_info.getAnswernum();
                int isUser = user_info.getIsuser();
                //判断分享次数
                if (isUser == 1) {  //用户是否已领取奖品
                    if (sharenum ==0) {
                        logger.info(id + "用户第" + (sharenum + 1) + "次分享，增加用户答题次数");
                        wechat_user userparm = new wechat_user();
                        userparm.setId(id);
                        userparm.setShare((byte) 1);
                        userparm.setSharenum(sharenum + 1);
                        userparm.setAnswernum(answernum + 2);
                        wechat_userMapper.updateByPrimaryKeySelective(userparm);

                    } else if (sharenum ==1) {
                        wechat_user userparm = new wechat_user();
                        userparm.setId(id);
                        userparm.setSharenum(sharenum + 1);
                        userparm.setAnswernum(answernum + 3);
                        wechat_userMapper.updateByPrimaryKeySelective(userparm);

                    } else {
                        logger.info("用户已分享过2次以上，不增加抽奖次数~");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        String [] str= MD5BASE64Util.base64decode(token).split(",");
      String openid=str[1];
        List<services> services=servicesMapper.selectByType(1); //获取已开启的指定客服信息
        if(wechat_userMapper.selectByopenid(openid)==null) {
            Integer index=0;
            Jedis jedis=new Jedis(redisconfig.getHost(),redisconfig.getPort());
            if(jedis.get("services_index_1")!=null){
                if(Integer.parseInt(jedis.get("services_index_1"))>=0) {
                    index = Integer.parseInt(jedis.get("services_index_1")) + 1;
                    jedis.set("services_index_1", index.toString());
                }
            }else {
                jedis.set("services_index_1",index.toString());

            }

            if(index>services.size()-1){
                jedis.set("services_index_1","0");
                index=0;
            }
            UUID uuid=UUID.randomUUID();
            wechat_user buyer = new wechat_user();
            buyer.setUuid( uuid.toString().split("-")[4].substring(0,6));
//            logger.info("当前客服列表："+services);
//            logger.info("当前下标:"+index);
            buyer.setServicesname(services.get(index).getName());
            buyer.setName(registerUserName);
//            String region = regionMapper.selectregion(jsonObject.getString("city")).getMergername();
//            String[] regionStr = region.split(",");
            buyer.setZone(jsonObject.getString("city"));
            buyer.setAvatarurl(jsonObject.getString("avatarUrl"));
            //默认答题数5
            buyer.setAnswernum(5);
            buyer.setNowanswer(0);
            buyer.setOpenid(str[1]);
            //分享次数
            buyer.setSharenum(0);
            wechat_userMapper.insertSelective(buyer);
            logger.info("用户注册成功,当前用户总数为："+wechat_userMapper.countmax());
            return ResultCode.SUCCESS.result();
        }else {
            return ResultCode.KEY_USER.result();
        }

    }











}
